package com.efounder.chat.activity;

import android.annotation.SuppressLint;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import androidx.constraintlayout.widget.ConstraintLayout;
import androidx.appcompat.app.AlertDialog;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.efounder.chat.R;
import com.efounder.chat.adapter.ShareToZoneImageAdapter;
import com.efounder.chat.event.ShareToZoneRefreshEvent;
import com.efounder.chat.model.ShareCloudFile;
import com.efounder.chat.model.ShareContent;
import com.efounder.chat.utils.HandleShareIntentUtil;
import com.efounder.chat.utils.ImageUtil;
import com.efounder.chat.utils.LXGlideImageLoader;
import com.efounder.chat.utils.PansoftCloudUtil;
import com.efounder.chat.utils.ThreadPoolUtils;
import com.efounder.constant.EnvironmentVariable;
import com.efounder.http.EFHttpRequest;
import com.efounder.util.LoadingDataUtilBlack;
import com.efounder.util.ToastUtil;
import com.efounder.utils.ResStringUtil;
import com.efounder.view.RoundFrameLayout;
import com.utilcode.util.DeviceUtils;
import com.utilcode.util.ToastUtils;

import org.greenrobot.eventbus.EventBus;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import static com.efounder.chat.utils.ImageUtil.chatpath;
import static com.efounder.frame.utils.Constants.CHAT_PASSWORD;
import static com.efounder.frame.utils.Constants.CHAT_USER_ID;

public class ShareToZoneActivity extends BaseActivity implements View.OnClickListener {

    public static final String BASE_URL = EnvironmentVariable.getProperty("OSPMZOneURL");
    private EditText etInput;
    private GridView gridView;
    private LinearLayout llPhoto;
    private ConstraintLayout clWebLayout;
    private RoundFrameLayout rflShareWebLayout;
    private ImageView webImage;
    private TextView webSubject, webTitle;
    private TextView etUrl;
    //    private WebView webView;
    private ShareToZoneImageAdapter adapter;
    //动态类型 说说为1 网页为2 初始为0，可以选择其他
    private int mDynamicType = 0;
    private String deviceModel;
    private ShareContent shareContent;
    /** 是否是app内的分享，是的话不显示留在星际通讯**/
    private boolean isLocalShare = false;
    /** 截屏分享的图片，轻微压缩 **/
    private boolean imageMinorCompress = false;

    private ArrayList<String> imgUrlList = new ArrayList<>();//图片的url list
    private ArrayList<ShareCloudFile> mPictureList = new ArrayList<>();//带进度的list
    //商品分享
    private TextView tvGoodText;
    private ImageView ivGoodImage;
    private TextView tvGoodProduce;
    private TextView tvGoodCome;
    private ImageView ivShopIcon;
    //是否正在发送中
    private boolean isSending;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_share_to_zone);

        initView();
        if (getIntent().getExtras() != null) {
            if (getIntent().getSerializableExtra("shareContent") != null) {
                if (getIntent().hasExtra("isLocalShare")) {
                    isLocalShare = getIntent().getBooleanExtra("isLocalShare", false);
                }
                if (getIntent().hasExtra("imageMinorCompress")) {
                    imageMinorCompress = getIntent().getBooleanExtra("imageMinorCompress", false);
                }
                shareContent = (ShareContent) getIntent().getSerializableExtra("shareContent");
                if (shareContent.getType() == HandleShareIntentUtil.SHARE_TYPE_WEB) {
                    mDynamicType = 2;
                } else if (shareContent.getType() == HandleShareIntentUtil.SHARE_TYPE_IMAGE ||
                        shareContent.getType() == HandleShareIntentUtil.SHARE_TYPE_TEXT){
                    imgUrlList.addAll(shareContent.getPictureList());
                    if (imgUrlList.size() > 0) {
                        for (String imgUrl : imgUrlList) {
                            ShareCloudFile shareCloudFile = new ShareCloudFile();
                            shareCloudFile.setCloudFilePath(imgUrl);
                            mPictureList.add(shareCloudFile);
                        }
                    }
                    mDynamicType = 1;
                } else {
                    //商城商品分享
                    mDynamicType = 5;
                }
                String text = shareContent.getText();
                if (text != null && !text.equals("")) {
                    etInput.setText(text);
                    etInput.setSelection(text.length());
                }
                deviceModel = DeviceUtils.getModel();
                isSending = false;

                resetType();
            }
        }
    }

    private void initView() {
        ImageView ivBack = (ImageView) findViewById(R.id.iv_back);
        ivBack.setVisibility(View.GONE);
        ImageView ivClose;
        TextView tvTitle;
        TextView tvSend;
        ivClose = (ImageView) findViewById(R.id.iv_close);
        ivClose.setVisibility(View.VISIBLE);//关闭按钮
        tvTitle = (TextView) findViewById(R.id.tv_title);
        tvTitle.setText(getResources().getString(R.string.share_to_zone));
        tvSend = (TextView) findViewById(R.id.tv_save);
        tvSend.setVisibility(View.VISIBLE);
        tvSend.setOnClickListener(this);
        etInput = (EditText) findViewById(R.id.et_input);
        llPhoto = (LinearLayout) findViewById(R.id.ll_photo);
        clWebLayout = (ConstraintLayout) findViewById(R.id.cl_webLayout);
        webImage = (ImageView) findViewById(R.id.imageview);
        webSubject = (TextView) findViewById(R.id.tvTitle);
        webTitle = (TextView) findViewById(R.id.tvMessage);
        //商品分享
        tvGoodText = (TextView) findViewById(R.id.tv_good_text);
        ivGoodImage = (ImageView) findViewById(R.id.iv_good_image);
        tvGoodProduce = (TextView) findViewById(R.id.tv_good_produce);
        tvGoodCome = (TextView) findViewById(R.id.tv_good_come);
        ivShopIcon = (ImageView) findViewById(R.id.iv_shop_icon);
//        etUrl = (TextView) findViewById(R.id.et_url);
//        webView = (WebView) findViewById(R.id.webView);
        gridView = (GridView) findViewById(R.id.gridview);
        tvSend.setText(R.string.chat_share);
        rflShareWebLayout = (RoundFrameLayout) findViewById(R.id.mobile_zone_content_mall_detail);
    }

    private void resetType() {
        //文字说说，照片说说
        if (mDynamicType == 1) {
            clWebLayout.setVisibility(View.GONE);
            llPhoto.setVisibility(View.VISIBLE);
            rflShareWebLayout.setVisibility(View.GONE);
            adapter = new ShareToZoneImageAdapter(this, mPictureList);
            gridView.setAdapter(adapter);
        } else if (mDynamicType == 2) {
            //网页说说，只有网页可点击
            llPhoto.setVisibility(View.GONE);
            rflShareWebLayout.setVisibility(View.GONE);
            clWebLayout.setVisibility(View.VISIBLE);
            webSubject.setText(shareContent.getSubject());
            webTitle.setText(shareContent.getText());
            LXGlideImageLoader.getInstance().displayImage(this, webImage, shareContent.getImgUrl(),
                    R.drawable.share_web);
//            if (JFStringUtil.isHttpUrl(shareWeb.getUrl())) {
//                LinearLayout.LayoutParams layoutParams =
//                        new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
//                                DisplayUtil.dip2px(ShareToZoneActivity.this, 300));
////                webView.setVisibility(View.VISIBLE);
////                webView.setLayoutParams(layoutParams);
//                if ((!shareWeb.getUrl().startsWith("http://")) && (!shareWeb.getUrl().startsWith("https://"))) {
//                    shareWeb.setUrl("https://" + shareWeb.getUrl());
//                }
//                //如果不设置WebViewClient，请求会跳转系统浏览器
////                webView.setWebViewClient(new WebViewClient() {
////                    //覆盖shouldOverrideUrlLoading 方法
////                    @Override
////                    public boolean shouldOverrideUrlLoading(WebView view, String url) {
////                        view.loadUrl(url);
////                        return true;
////                    }
////                });
////                webView.loadUrl(text);
//                etUrl.setText(shareWeb.getUrl());
//            }
        } else if (mDynamicType == 5) {
            //商品分享到引力场
            llPhoto.setVisibility(View.GONE);
            clWebLayout.setVisibility(View.GONE);
            rflShareWebLayout.setVisibility(View.VISIBLE);
            String goodUrl = shareContent.getGoodUrl();
            try {
                JSONObject goodObject = new JSONObject(goodUrl);
                tvGoodText.setText(goodObject.optString("title"));
                tvGoodProduce.setText(goodObject.optString("price"));
                tvGoodCome.setText(goodObject.optString("from"));
                LXGlideImageLoader.getInstance().displayRoundCornerImage(this,ivGoodImage,goodObject.optString("goodCover"),0,0,6);
                LXGlideImageLoader.getInstance().displayRoundCornerImage(this,ivShopIcon,goodObject.optString("shopIcon"),0,0,6);
            } catch (JSONException e) {
                e.printStackTrace();
            }

        }

    }

    @Override
    public void onClick(View v) {
        int id = v.getId();
        if (id == R.id.tv_save) {
            //发送
            if (isSending) {
                ToastUtil.showToast(ShareToZoneActivity.this, R.string.chat_sending);
                return;
            }
            String content = etInput.getText().toString();
            sendNewDynamic(content);
        }
    }

    /**
     * 发送新动态
     *
     * @param content 说说内容
     */
    @SuppressLint("NewApi")
    private void sendNewDynamic(String content) {
        isSending = true;
        // 类型为说说
        if (mDynamicType == 1 || mDynamicType == 0) {
//            文字 图片都为空
            if ("".equals(content) && mPictureList.size() == 0) {
                ToastUtil.showToast(this, R.string.chat_content_empty);
                isSending = false;
            }

            // 图片不为空
            else if (mPictureList.size() > 0) {
                LoadingDataUtilBlack.show(this, ResStringUtil.getString(R.string.chat_ready_upload));
                //压缩图片上传
                ThreadPoolUtils.execute(new ThreadPoolUtils.Task() {
                    @Override
                    protected void work() {
                        if (mPictureList.size() == 1) {
                            String imgLocation = mPictureList.get(0).getCloudFilePath();
                            //是gif图 不压缩
                            if (ImageUtil.isGifFile((new File(imgLocation)))) {
                                uploadOneImage(imgLocation, ImageUtil.getPicScale(imgLocation));
                            } else {
                                String scale;
                                if (imageMinorCompress) {
                                    scale = ImageUtil.saveNewImageOld(imgLocation, 2560, 2560);
                                } else {
                                    scale = ImageUtil.saveNewImage(imgLocation, 1280, 1280);
                                }
                                String img = chatpath + ImageUtil.getFileName(imgLocation) + ".pic";
                                if (scale == null) {
                                    scale = "";
                                }
                                uploadOneImage(img, scale);
                            }
                        } else {
                            ArrayList<ShareCloudFile> uploadCloudFiles = new ArrayList<>();
                            for (ShareCloudFile imgAddress : mPictureList) {
                                imgAddress.setCloudProgress(0);
                                //如果不是gif动图则进行裁剪压缩
                                if (!ImageUtil.isGifFile((new File(imgAddress.getCloudFilePath())))) {
                                    if (imageMinorCompress) {
                                        ImageUtil.saveNewImageOld(imgAddress.getCloudFilePath(), 2560, 2560);
                                    } else {
                                        ImageUtil.saveNewImage(imgAddress.getCloudFilePath(), 1280, 1280);
                                    }

                                    imgAddress.setCloudFilePath(chatpath + ImageUtil.getFileName(imgAddress.getCloudFilePath()) + ".pic");
                                    uploadCloudFiles.add(imgAddress);
//                            uploadImage(chatpath + ImageUtil.getFileName(imgAddress) + ".pic");
                                } else {
//                            uploadImage(imgAddress);
                                    imgAddress.setCloudFilePath(imgAddress.getCloudFilePath());
                                    uploadCloudFiles.add(imgAddress);
                                }
                            }
                            PansoftCloudUtil.syncMultiFileUpload(uploadCloudFiles, new PansoftCloudUtil.MultiUpLoadListener() {
                                @Override
                                public void uploadProgress(int position, int progress, PansoftCloudUtil.CloudFile cloudFile) {
                                    if (isFinishing() || isDestroyed()) {
                                        return;
                                    }
                                    Log.d("SendPost", position + "---" + progress);
                                    mPictureList.get(position).setCloudProgress(progress);
                                    adapter.notifyDataSetChanged();
                                }

                                @Override
                                public void upLoadFinish(List<String> urlList, List<? extends PansoftCloudUtil.CloudFile> cloudFileList) {
                                    if (isFinishing() || isDestroyed()) {
                                        return;
                                    }
                                    sendImg(urlList);
                                }

                                @Override
                                public void uploadFail(Object message) {
                                    ToastUtil.showToast(ShareToZoneActivity.this, R.string.chat_send_error_retry);
                                    isSending = false;
                                }
                            });
                        }
                    }
                });

            } else {
                //图片为空
                sendOnlyText();
            }
        } else if (mDynamicType == 2) {
            String urlStr = shareContent.getUrl();
            //网页说说
            if ("".equals(urlStr)) {
                ToastUtil.showToast(this, R.string.chat_web_empty);
                isSending = false;
            } else {
                sendUrl();
            }
        } else if (mDynamicType == 5) {
            sendMallShare();
        }
    }

    /**
     * 上传单张图片并发送
     *
     * @param imgLocation 图片本地路径
     * @param scale       图片宽高比
     */
    @SuppressLint("NewApi")
    private void uploadOneImage(String imgLocation, String scale) {
        String[] scales = scale.split(":");
        final String strWidth = scales[0];
        final String strHeight = scales[1];

        final List<String> imglist = new ArrayList<>();

        PansoftCloudUtil.cloudUploadWithProgress(imgLocation, new PansoftCloudUtil.UpLoadListener() {
            @Override
            public void getHttpUrl(Boolean isSuccess, String url) {
                if (isFinishing() || isDestroyed()) {
                    return;
                }
                if (isSuccess) {
                    Log.i(TAG, "---头像在云盘服务器上的路径:" + url);
                    imglist.add(url);
//                    LoadingDataUtilBlack.dismiss();
                    String contentText = etInput.getText().toString();
                    String content = createSingleImageContent(contentText, imglist, Integer.valueOf(strWidth), Integer.valueOf(strHeight));
                    sendPost(content);
                    isSending = false;
                } else {
//                    LoadingDataUtilBlack.dismiss();
                    isSending = false;
                    ToastUtil.showToast(ShareToZoneActivity.this, R.string.chat_send_error_retry);
                }
            }
        }, new PansoftCloudUtil.ProgressListener() {
            @Override
            public void progress(String path, int percent) {
                if (isFinishing() || isDestroyed()) {
                    return;
                }
                mPictureList.get(0).setCloudProgress(percent);
                adapter.notifyDataSetChanged();
            }
        });
    }

    /**
     * 只发送文字
     */
    private void sendOnlyText() {
        String contentText = etInput.getText().toString();
        String content = createCommonContent(contentText, new ArrayList<String>());
        sendPost(content);
        isSending = false;
    }

    /**
     * 发送图片
     */
    private void sendImg(List<String> imgUrlList) {
        String contentText = etInput.getText().toString();
        String content = createCommonContent(contentText, imgUrlList);
        sendPost(content);
        isSending = false;
    }

    /**
     * 发送网址
     */
    private void sendUrl() {
        String contentText = etInput.getText().toString();
        String urlText = shareContent.getUrl();
        String content = createWebContent(contentText, urlText);
        sendPost(content);
        isSending = false;
        //showAlertDialog(true, "分享成功");
//        finish();

    }

    private void sendMallShare() {
        String text = etInput.getText().toString();
        String mallContent = shareContent.getGoodUrl();
        String content = createMallShareContent(text, mallContent);
        if ("".equals(content)) {
            ToastUtils.showShort(R.string.mall_share_error_retry);
            return;
        }
        sendPost(content);
        isSending = false;
    }

    private String createSingleImageContent(String text, List<String> images, int width, int height) {
        HashMap<String, Object> content = new HashMap<>();
        content.put("images", new JSONArray(images));
        content.put("text", text);
        content.put("type", 2);
        content.put("width", width);
        content.put("height", height);
        return String.format("%s", new JSONObject(content).toString());
    }

    private String createCommonContent(String text, List<String> images) {
        HashMap<String, Object> content = new HashMap<>();
        content.put("images", new JSONArray(images));
        content.put("text", text);
        content.put("type", images.size() == 0 ? 1 : 2);
        return String.format("%s", new JSONObject(content).toString());
    }

    private String createWebContent(String text, String url) {
        HashMap<String, Object> content = new HashMap<>();
        content.put("text", text);
        content.put("type", 4);
        HashMap<String, Object> urlMap = new HashMap<>();
        urlMap.put("url", url);
        urlMap.put("height", 300);
        content.put("web", new JSONObject(urlMap));
        return String.format("%s", new JSONObject(content).toString());
    }

    private String createMallShareContent(String text, String goodContent) {
        try {
            HashMap<String, Object> content = new HashMap<>();
            content.put("text", text);
            content.put("type", 5);
            content.put("goods", new JSONObject(goodContent));
            return String.format("%s", new JSONObject(content).toString());
        } catch (Exception e) {
            e.printStackTrace();
            return "";
        }
    }

    /**
     * 发说说
     *
     * @param content 说说内容
     */
    private void sendPost(String content) {
        LoadingDataUtilBlack.show(this,ResStringUtil.getString(R.string.chat_launching));
        HashMap<String, String> params = new HashMap<>();
        params.put("userid", EnvironmentVariable.getProperty(CHAT_USER_ID));
        params.put("password", EnvironmentVariable.getProperty(CHAT_PASSWORD));
        params.put("device", deviceModel);
        params.put("content", content);

        EFHttpRequest httpRequest = new EFHttpRequest(TAG);
        httpRequest.setHttpRequestListener(new EFHttpRequest.HttpRequestListener() {
            @Override
            public void onRequestSuccess(int requestCode, String response) {
                LoadingDataUtilBlack.dismiss();
                if (response != null) {
                    try {

                        JSONObject jsonObject = new JSONObject(response);
                        if ("101000".equals(jsonObject.optString("status"))) {
//                            ToastUtils.showShort("分享成功");
//                            finish();
                            if (isLocalShare) {
                                showLocalSuccessAlert();
                            } else {
                                showAlertDialog(true, ResStringUtil.getString(R.string.chat_share_success));
                            }

                        } else {

                            ToastUtils.showShort(R.string.chat_share_fail);
                        }

                    } catch (Exception e) {
                        e.printStackTrace();
                        ToastUtils.showShort(R.string.chat_share_fail);
                    }
                }
            }

            @Override
            public void onRequestFail(int requestCode, String message) {
                LoadingDataUtilBlack.dismiss();
                ToastUtils.showShort(R.string.chat_share_fail);
            }
        });
        httpRequest.httpPost(String.format("%s%s", BASE_URL, "shortposts"), params);
    }

    /**
     * 显示确定，点击返回
     * TODO 显示进入引力场
     */
    private void showLocalSuccessAlert() {
        AlertDialog dialog = new androidx.appcompat.app.AlertDialog.Builder(this).setTitle(ResStringUtil.getString(R.string.common_text_hint))
                .setMessage(ResStringUtil.getString(R.string.chat_publish_ss_success))
                .setCancelable(false)
                .setPositiveButton(R.string.common_text_confirm, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                        EventBus.getDefault().postSticky(new ShareToZoneRefreshEvent());
                        finish();
//                        if (success) {
//                            finish();
//                        } else {
//                            dialog.dismiss();
//                        }

                    }
                }).create();
//        if (success) {
//            dialog.setButton(AlertDialog.BUTTON_POSITIVE, ResStringUtil.getString(R.string.chat_into_gravity_field), new DialogInterface.OnClickListener() {
//                @Override
//                public void onClick(DialogInterface dialog, int which) {
//                    dialog.dismiss();
//                    try {
//                        String className = getResources().getString(R.string.from_group_backto_first);
//                        Class clazz = Class.forName(className);
//                        Intent myIntent = new Intent(ShareToZoneActivity.this, clazz);
//                        myIntent.putExtra("shareToZone", true);
//                        startActivity(myIntent);
//                        EventBus.getDefault().postSticky(new ShareToZoneRefreshEvent());
//                        finish();
//                    } catch (ClassNotFoundException e) {
//                        e.printStackTrace();
//                    }
//                }
//            });
            dialog.show();
//        }
    }

    /**
     * @param success 是否分享成功
     * @param message 信息
     */
    public void showAlertDialog(final boolean success, String message) {
        AlertDialog dialog = new androidx.appcompat.app.AlertDialog.Builder(this).setTitle(ResStringUtil.getString(R.string.common_text_hint))
                .setMessage(message)
                .setCancelable(false)
                .setNegativeButton(R.string.common_text_back, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                        EventBus.getDefault().postSticky(new ShareToZoneRefreshEvent());
                        finish();
//                        if (success) {
//                            finish();
//                        } else {
//                            dialog.dismiss();
//                        }

                    }
                }).create();
        if (success) {
            dialog.setButton(AlertDialog.BUTTON_POSITIVE, ResStringUtil.getString(R.string.chat_stay_in) + getString(R.string.app_name), new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    dialog.dismiss();
                    try {
                        String className = getResources().getString(R.string.from_group_backto_first);
                        Class clazz = Class.forName(className);
                        Intent myIntent = new Intent(ShareToZoneActivity.this, clazz);
                        myIntent.putExtra("shareToZone", true);
                        startActivity(myIntent);
                        EventBus.getDefault().postSticky(new ShareToZoneRefreshEvent());
                        finish();
                    } catch (ClassNotFoundException e) {
                        e.printStackTrace();
                    }
                }
            });
            dialog.show();
        }

    }
}
